$(document).ready(
		function() {
			var elementEdit = 'user';
			var element = '#'+elementEdit;
			var urlAction = '/'+elementEdit;
			var reloadData = function(){
				$(element).jqGrid('setGridParam', {
					datatype : 'json'
				}).trigger('reloadGrid', [ {
					page : 1
				} ]);
			}
			
			String.prototype.beginsWith = function (string) {
			    return(this.indexOf(string) === 0);
			};
			
			var checkValidAdd = function(value) {
				var check = false;
				$.ajax({
					url : "/user",
					async : false,
					type : "GET",
					success : function(resp) {
						var data = resp.data;
						for ( var i = 0; i < data.length; i++) {
							if (value == data[i].name) {
								check = false;
								return;
							}
						}
						check = true;
						return;
					}
				});
				return check;
			}
			jQuery(element).jqGrid(
					{
						url : urlAction,
						datatype : "json",
						height : "auto",
						width : "auto",
						colNames : [ 'Tên Đăng Nhập', 'Mật Khẩu', 'Phân Quyền', 'Thao Tác' ],
						colModel : [ {
							name : 'name',
							index : 'name',
							width : 200,
							editable : true,
							editoptions : {
								readonly : true,
								dataEvents : [ {
									type : 'change',
									fn : function(e) {
										if ($(e.target).is('.FormElement')) {   
		                                    var form = $(e.target).closest('form.FormGrid');
		                                    var user = $("input#name.FormElement", form[0]).val();
		                                    if (!user.beginsWith('NV')) {
		                                    	$("input#name.FormElement", form[0]).val("NV"+user);
		                                    }
		                                }
									}
								} ]
							},
							editrules : {
								required : true
							},
							searchoptions : {
								sopt : [ 'bw', 'eq', 'ne', 'ew', 'cn' ]
							},
							jsonmap : "name"
						},{
							name : 'userPassword',
							index : 'userPassword',
							width : 200,
							editable : true,
							hidden: true,
							editrules : {
								required : true,
								edithidden:true
							},
							edittype : "password",
							searchoptions : {
								sopt : [ 'bw', 'eq', 'ne', 'ew', 'cn' ]
							},
							jsonmap : "userPassword"
						}, {
							name : 'userRole',
							index : 'userRole',
							width : 150,
							editable : true,
							editrules : {
								required : true,
							},
							edittype : "select",
							searchoptions : {
								sopt : [ 'bw', 'eq', 'ne', 'ew', 'cn' ]
							},
							stype: "select",
							searchoptions : {
								sopt : ['bw'],
								value: ":Tất Cả;Admin:Admin;Super User:Super User",
								dataEvents : [ {
									type : 'change',
									fn : function(e) {
										if (!$(e.target).is('.input-elm')) {   
											var sgrid = $(element)[0];
											sgrid.triggerToolbar();
		                                }
									}
								} ]
							},
							editoptions : {
								value: "Admin:Admin;Super User:Super User"
							},
							jsonmap : "userRole"
						},{
							name : 'myac',
							width : 80,
							fixed : true,
							sortable : false,
							resize : false,
							search : false,
							formatter : 'actions',
							formatoptions : {
								keys : true,
								afterSave:function(rowid) {
									reloadData();
					            }
							}
						} ],
						ignoreCase : true,
						rowNum : 20,
						rowList : [ 20, 30, 50, 100000000 ],
						loadonce : true,
						mtype : "GET",
						multiselect: true,
						rownumbers : true,
						rownumWidth : 40,
						gridview : true,
						pager : element+'pager',
						sortname : 'name',
						viewrecords : true,
						sortorder : "asc",
						editurl : urlAction,
						caption : "Danh Sách Tài Khoản Hệ Thống",
						jsonReader : {
							root : 'data',
							id : 'name',
							repeatitems : false,
							page : function(obj) {
								return 1;
							},
							total : function(obj) {
								return 1;
							},
							records : function(obj) {
								return obj.length;
							},
						},
						loadComplete : function() {
							$("option[value=100000000]").text('All');
						},
						ondblClickRow : function(rowid) {
							jQuery(element).jqGrid('editGridRow', rowid, {
								// recreateForm : true,
								closeAfterEdit : true,
								closeOnEscape : true,
								reloadAfterSubmit : false,
								afterSubmit: function () {
									reloadData();
									return [true];
								},
								beforeShowForm : function(formid) {
									$('#name',formid[0]).attr('readonly', 'readonly');
								}
							});
						}
					});
			jQuery(element).jqGrid('navGrid', element+'pager', {
				view : false,
				excel : true,
				beforeRefresh : function() {
					reloadData();
				}
			},
			// edit option
			{
				beforeShowForm : function(formid) {
					$('#name',formid[0]).attr('readonly', 'readonly');
				},
				checkOnSubmit : true,
				closeAfterAdd : true,
				closeAfterEdit : true,
				afterSubmit: function () {
					reloadData();
					return [true];
				}
			},
			// add option
			{
				beforeShowForm : function(formid) {
					$('#name',formid[0]).removeAttr('readonly');
				},
				closeAfterAdd : true,
				closeAfterEdit : true,
				beforeSubmit : function(postdata, formid) {
					if (checkValidAdd(postdata.name))
						return [ true, "", "" ];
					else
						return [ false, "Tên đăng nhập đã tồn tại!", "" ];
				},
				afterSubmit: function () {
					reloadData();
					return [true];
				}
			}, 
			//delete option
			{
				afterSubmit: function (response, postdata) {
					reloadData();
					if(response.responseText == "")
						return [true];
					else
						return[false, response.responseText, ""];
				}
			},
			// search option
			{
				multipleSearch : true,
				closeAfterSearch : true,
			// onInitializeSearch : updateGroupOpText,
			// afterRedraw : updateGroupOpText
			});
			jQuery(element).jqGrid('gridResize', {
				minWidth : 400,
				maxWidth : 1000,
				minHeight : 100,
				maxHeight : 500
			});
			// add filter toolbar
			jQuery(element).jqGrid('filterToolbar', {
				stringResult : true,
				searchOnEnter : false,
				defaultSearch : "bw"
			});
			jQuery(element).jqGrid('navButtonAdd', element+'pager', {
				id : 'pager_excel',
				caption : '',
				title : 'Xuất File Excel',
				onClickButton : function(e) {
					exportData(elementEdit);
				},
				buttonicon : 'ui-icon-disk'
			});
			jQuery(element).jqGrid('navButtonAdd', element+'pager', {
				id : 'pager_reorder_column',
				caption : '',
				title : 'Chỉnh Sửa Bảng',
				onClickButton : function(e) {
					jQuery(element).jqGrid('columnChooser', {
						width : 500
					});
				},
				buttonicon : 'ui-icon-newwin'
			});

		});
